module sw.main;
import nazo.http, nazo.string, nazo.stdio, std.uri, nazo.env;
import sw.locale.locale, sw.locale.localefactory, sw.siteconfig, sw.mode, sw.modelist, sw.client, sw.locale.locale;

static struct CGI{
  private static invariant(string[sw.locale.locale.Locale.EnumLength])* _locale;
  static struct locale{
    ///FIXME: ASTマクロ、もしくはalways_inlineにするべき
    static string getValue(uint num)(){
      return (*_locale)[num];
    }
  }
}

version(build){
  pragma(target, "index.cgi.dummy");//拡張子部分がカットされてしまう…
  //pragma(lib, zlib);
}

///main
int main(string[] args){
  debug{}else{
    if(Env.TGet!("SERVER_PORT")()==""){ //cgiとして実行されなければ
      writefln("Error: please use as cgi");
      return 0;
    }
  }

  debug writef(\n\n);
  SiteConfig cfg = SiteConfig("site.cfg");

  debug{}else{
    if(!Http.isAllowMethod()){
      HttpResponse.write("Security Error!", 403);
      return 0;
    }
  }

  CGI._locale = LocaleFactory.getLocale(Http.acceptLanguage().getBefore(',').getBefore(';'));

  Client.init(&cfg);

  auto t="mode" in Http.query;
  string strmode=t?decodeComponent(*t):"";
  string pref;
  int i=strmode.find(':');
  if(i!=-1){
      pref=strmode[0..i];
      strmode=strmode[i+1..$];
  }
  try{
    ModeFactoryFactory.getModeFactory(&cfg, pref).getMode(strmode).responds();
  }catch(SecurityException e){
    HttpResponse.write("Security Error!", 403);
  }catch(Exception e){
    HttpResponse.write(e.msg);
  }
  return 0;
}
